package com.example.sharesinfo.fragment.stock;


import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.example.sharesinfo.R;
import com.example.sharesinfo.adapter.ScrollablePanelAdapter;
import com.example.sharesinfo.manager.DialogManager;
import com.example.sharesinfo.model.ColumnTitle;
import com.example.sharesinfo.model.DataInfo;
import com.example.sharesinfo.model.HKStockModel;
import com.example.sharesinfo.model.StockInfo;
import com.example.sharesinfo.ui.SharesInfoActivity;
import com.example.sharesinfo.utils.LogUtils;
import com.example.sharesinfo.utils.OkHttpUtils;
import com.example.sharesinfo.view.CustomRadioGroup;
import com.google.gson.JsonObject;
import com.kelin.scrollablepanel.library.ScrollablePanel;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * A simple {@link Fragment} subclass.
 */
public class MarketHongKongStocksFragment extends Fragment implements RadioGroup.OnCheckedChangeListener {
    /**
     * 把所有的单独股票改成recycleview填充
     * AH没有做
     */
    private String LogTag = "MarketHongKongStocksFragment:";
    private ScrollablePanel scrollablePanel;
    private ScrollablePanelAdapter scrollablePanelAdapter;
    private List<HKStockModel> mList = new ArrayList<>();


    //港股类型radiogroup
    private RadioGroup rank_type;
    private int type0 = 0;
    private int type1 = 0;
    private int type2 = 0;
    private int type3 = 0;
    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case 200:
                    if (mList.size() > 0) {
                        mList.clear();
                    }
                    JSONArray result = (JSONArray) msg.obj;
                    for (int i = 0; i < result.length(); i++) {
                        try {
                            HKStockModel model = new HKStockModel();
                            JSONObject object = (JSONObject) result.get(i);
                            model.setCode(object.getString("代码"));
                            model.setStockName(object.getString("股票名称"));
                            LogUtils.i(LogTag + object.getString("股票名称"));
                            model.setNewRate(object.getString("最新"));
                            model.setRiseAdownPrice(object.getString("涨跌额"));
                            model.setRiseAdownRange(object.getString("涨跌幅"));
                            model.setToday(object.getString("今开"));
                            model.setYesterday(object.getString("昨收"));
                            model.setHighest(object.getString("最高"));
                            model.setMinimum(object.getString("最低"));
                            model.setVolume(object.getString("成交量（股）"));
                            model.setTurnover(object.getString("成交额（港元）"));
                            mList.add(model);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    generateTestData(mList);
                    break;
                case 201:


                    break;
                case 404:
                    Toast.makeText(getContext(), "获取数据失败", Toast.LENGTH_SHORT).show();
                    break;

            }
            return false;
        }
    });

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_market_hong_kong_stocks, null);

        initView(view);
        initData();
        return view;
    }

    private void initData() {

        List<ColumnTitle> columnTitleList = new ArrayList<>();

        String column1 = "最新";
        String column2 = "涨跌额";
        String column3 = "涨跌幅";
        String column4 = "今开";
        String column5 = "最高";
        String column6 = "最低";
        String column7 = "昨收";
        String column8 = "成交量";
        String column9 = "成交额";
        ColumnTitle columnTitle1 = new ColumnTitle();
        columnTitle1.setColumnTitle(column1);
        columnTitleList.add(columnTitle1);
        ColumnTitle columnTitle2 = new ColumnTitle();
        columnTitle2.setColumnTitle(column2);
        columnTitleList.add(columnTitle2);
        ColumnTitle columnTitle3 = new ColumnTitle();
        columnTitle3.setColumnTitle(column3);
        columnTitleList.add(columnTitle3);
        ColumnTitle columnTitle4 = new ColumnTitle();
        columnTitle4.setColumnTitle(column4);
        columnTitleList.add(columnTitle4);
        ColumnTitle columnTitle5 = new ColumnTitle();
        columnTitle5.setColumnTitle(column5);
        columnTitleList.add(columnTitle5);
        ColumnTitle columnTitle6 = new ColumnTitle();
        columnTitle6.setColumnTitle(column6);
        columnTitleList.add(columnTitle6);

        ColumnTitle columnTitle7 = new ColumnTitle();
        columnTitle7.setColumnTitle(column7);
        columnTitleList.add(columnTitle7);

        ColumnTitle columnTitle8 = new ColumnTitle();
        columnTitle8.setColumnTitle(column8);
        columnTitleList.add(columnTitle8);

        ColumnTitle columnTitle9 = new ColumnTitle();
        columnTitle8.setColumnTitle(column9);
        columnTitleList.add(columnTitle9);

        scrollablePanelAdapter.setColumnTitleList(columnTitleList);

    }

    private void initView(View view) {
        scrollablePanel = view.findViewById(R.id.hong_kong_stocks_scrollable_panel);
        scrollablePanelAdapter = new ScrollablePanelAdapter(0,new ScrollablePanelAdapter.OnBindDataListener() {
            @Override
            public void onBindViewHolder(RecyclerView.ViewHolder holder, final int row, int column) {
                int viewType = scrollablePanelAdapter.getItemViewType(row, column);
                switch (viewType) {
                    case ScrollablePanelAdapter.COLUMN_TITLE_TYPE:
                        scrollablePanelAdapter.setColumnTitleView(column, (ScrollablePanelAdapter.ColumnTitleViewHolder) holder);
                        break;
                    case ScrollablePanelAdapter.STOCK_TYPE:
                        scrollablePanelAdapter.setStockView(row, (ScrollablePanelAdapter.StockViewHolder) holder);
                        holder.itemView.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                SharesInfoActivity.startActivity(getContext(), mList.get(row - 1).getCode());
                            }
                        });
                        break;
                    case ScrollablePanelAdapter.DATA_TYPE:
                        scrollablePanelAdapter.setDataView(row, column, (ScrollablePanelAdapter.DataViewHolder) holder);
                        break;
                    case ScrollablePanelAdapter.TITLE_TYPE:
                        break;
                }

            }
        });
        scrollablePanel.setPanelAdapter(scrollablePanelAdapter);
        rank_type = view.findViewById(R.id.hong_kong_stocks_radio_group);
        rank_type.setOnCheckedChangeListener(this);
        //这里页数没有处理
        querydatas(0, 0);


    }

    private void querydatas(int page, int index) {
        /**
         * index 0: 知名港股
         * index 1: AH股
         * index 2: 港股主板
         * index 3: 港股创业板块
         */
        String url = "";
        if (index == 0) {
            //知名港股
            url = "http://119.23.221.142/api/stock/GetWellknownHKStockList?Page=1";
        } else if (index == 1) {
            //AH股

        } else if (index == 2) {
            //港股主板
            url = "http://119.23.221.142/api/stock/GetHKStocksMainBoardList?Page=1";
        } else if (index == 3) {
            //港股创业板块
            url = "http://119.23.221.142/api/stock/GetHKChuangYeBoardList?Page=1";
        }
        OkHttpUtils.getInstance().Get(url, new OkHttpUtils.okHttpListener() {
            Message message = mHandler.obtainMessage();

            @Override
            public void OnSuccess(String s, int code) throws JSONException {
                message.what = code;
                JSONObject object = new JSONObject(s);
                JSONArray array = object.getJSONArray("data");
                message.obj = array;

                mHandler.sendMessage(message);
                LogUtils.i(LogTag + object.getString("data"));
            }

            @Override
            public void OnFailed(String s) {
                message.what = 404;
                message.obj = s;
                mHandler.sendMessage(message);
            }
        });
    }

    private void generateTestData(List<HKStockModel> list) {


        List<StockInfo> stockInfoList = new ArrayList<>();
        List<List<DataInfo>> dataList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            HKStockModel model = list.get(i);
            StockInfo stockInfo = new StockInfo();
            stockInfo.setStockName(model.getStockName());
            LogUtils.i(LogTag + model.getStockName());
            stockInfo.setRoomId(i);
            stockInfo.setStockId(model.getCode());
            stockInfoList.add(stockInfo);
            addData(model, dataList);

        }
        scrollablePanelAdapter.setStockInfoList(stockInfoList);
        scrollablePanelAdapter.setDataList(dataList);

        scrollablePanel.notifyDataSetChanged();
    }

    private void addData(HKStockModel model, List<List<DataInfo>> dataList) {
        List<DataInfo> dataInfoList = new ArrayList<>();
        DataInfo dataInfo1 = new DataInfo();
        dataInfo1.setData(model.getNewRate());
        dataInfoList.add(dataInfo1);

        DataInfo dataInfo2 = new DataInfo();
        dataInfo2.setData(model.getRiseAdownPrice());
        dataInfoList.add(dataInfo2);

        DataInfo dataInfo3 = new DataInfo();
        dataInfo3.setData(model.getRiseAdownRange());
        dataInfoList.add(dataInfo3);

        DataInfo dataInfo4 = new DataInfo();
        dataInfo4.setData(model.getToday());
        dataInfoList.add(dataInfo4);

        DataInfo dataInfo5 = new DataInfo();
        dataInfo5.setData(model.getHighest());
        dataInfoList.add(dataInfo5);

        DataInfo dataInfo6 = new DataInfo();
        dataInfo6.setData(model.getMinimum());
        dataInfoList.add(dataInfo6);

        DataInfo dataInfo7 = new DataInfo();
        dataInfo7.setData(model.getYesterday());
        dataInfoList.add(dataInfo7);

        DataInfo dataInfo8 = new DataInfo();
        dataInfo8.setData(model.getVolume());
        dataInfoList.add(dataInfo8);

        DataInfo dataInfo9 = new DataInfo();
        dataInfo9.setData(model.getTurnover());
        dataInfoList.add(dataInfo9);

        dataList.add(dataInfoList);
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.hong_kong_stocks_rb_1:
                if (type0 == 0) {
                    querydatas(0, 0);
                    type0 = 1;
                    type1 = 0;
                    type2 = 0;
                    type3 = 0;
                }
                break;
            case R.id.hong_kong_stocks_rb_3:
                querydatas(0, 2);
                type0 = 0;
                type1 = 0;
                type2 = 1;
                type3 = 0;
                break;
            case R.id.hong_kong_stocks_rb_4:
                querydatas(0, 3);
                type0 = 0;
                type1 = 0;
                type2 = 0;
                type3 = 1;
                break;
        }
    }
}
